package com.algorithm.code.list;

/**
 * @program: study
 * @className: CycleList
 * @description: TODO
 * @author: kukuxiahuni
 * @create: 2020-01-19 11:39
 * @version: v1.0
 **/
public class CycleList<T> implements BaseList<T> {

    /**
     * 头结点
     */
    private final Node<T> head = new Node<>(null, null);

    /**
     *
     */
    private Node<T> tail = head;

    public static void main(String[] args) {
        CycleList<Integer> cycleList = new CycleList<>();
        for (int i = 0; i < 20; ++i) {
            cycleList.add(i);
        }

        cycleList.deleteFirst(1);
        cycleList.deleteFirst(0);
        cycleList.deleteFirst(10);
        cycleList.deleteFirst(19);
        cycleList.printAll();
    }

    /**
     * 功能描述: 删除节点时要注意尾指针的移动
     * @param:
     * @return:
     * @auther: kukuxiahuni
     * @date: 2020/1/21 4:44 下午
     * @modify_auther: kukuxiahuni
     * @modify_time: 2020/1/21 4:44 下午
     **/
    @Override
    public void deleteFirst(T value) {
        if (value == null) {
            return;
        }

        if (isEmpty()) {
            return;
        }
//
//        /**
//         * 1. 判定头指针
//         */
//        if (head.next.value.equals(value)) {
//            head.next = head.next.next;
//            return;
//        }

        Node<T> p = head;
        while (p.next != tail) {

            Node<T> q = p.next;
            if (q.value.equals(value)) {
                p.next = q.next;
                return;
            }
            p = p.next;
        }

        if (tail.value.equals(value)) {
            p.next = tail.next;
            tail = p;
            return;
        }
    }

    @Override
    public void add(T value) {

        if (value == null) {
            return;
        }

        Node node = new Node(value, head.next);
        tail.next = node;
        tail = node;

    }

    @Override
    public boolean isEmpty() {
        return tail.next == null;
    }

    @Override
    public void printAll() {

        Node<T> p = head.next;
        while (p != tail) {
            System.out.println(p.value);
            p = p.next;
        }
        System.out.println(p.value);
    }

}
